import 'dart:async';
import 'dart:convert';
import 'dart:ffi';
import 'dart:io';

import 'package:gate_cli/utils/process_util.dart';
import 'package:gate_cli/exception/errors.dart';

/// Author: Shper
/// Created: 2024/4/29
/// Description: TODO
class PubspecUtil {

  /// 重置项目工程
  static Future<void> recordsPubspecLockFile() async {
    // 判断 assets 目录是否存在，不存在时 创建
    var assetsDir = Directory('${Directory.current.path}/assets');
    if (!assetsDir.existsSync()) {
      assetsDir.createSync(recursive: true);
    }

    // 拷贝 lock 文件，并且剔除里面 url
    var lockFilePath = '${Directory.current.path}/assets/pubspec.txt';
    final cpLockFileSuccess = await ProcessUtil.startProcess("cp", [
      '-r',
      '${Directory.current.path}/pubspec.lock',
      lockFilePath
    ]);
    print('run pubspec.lock copy : $cpLockFileSuccess');
    if (!cpLockFileSuccess) throw new CommandRunError('拷贝 pubspec.lock 失败，，请确认 lock 文件是否正常');

    try {
      var file = File(lockFilePath);
      var lines = file.readAsLinesSync();
      var resultLines = '';

      // 添加分支、commit、编译时间信息
      // 获取当前 分支名
      var currentBranchName = ProcessUtil.runProcessAndResult('git', ['rev-parse', '--abbrev-ref','HEAD']) as String;
      // 获取当前 commit 信息
      var currentCommit = ProcessUtil.runProcessAndResult('git', ['rev-parse', 'HEAD']) as String;
      // 获取当前 编译时间
      var buildTime = DateTime.now().toString();
      resultLines = "BuildInfo:\n    branch: $currentBranchName\n    commit: $currentCommit\n    buildTime: $buildTime\n\n";

      lines.forEach((content) {
        // 去掉 url 地址
        if (!content.trim().startsWith('url:')) {
          resultLines += "\n${content}";
        }
      });
      file.writeAsStringSync(resultLines);
    } catch (e) {
      throw new CommandRunError('读写 pubspec.lock 失败，请确认 lock 请确认文件是否正常');
    }
  }

}